﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Threading.Tasks;
using YiYiTong.Rocket.Helper;

namespace YiYiTong.Rocket.Business
{
    public class ImageFileBiz
    {
        public static string GetImg(string key, string imgstyle = "")
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                if (key.ToLower().StartsWith("http://") || key.ToLower().StartsWith("https://"))
                    return key;
                else
                    return AliyunOssBiz.GetImg(key, imgstyle);
            }
            else
                return "";
        }

        /// <summary>
        /// 图片上传aly
        /// </summary>
        /// <returns></returns>
        public static Tuple<bool, string, string> UpImg(HttpPostedFile file, string dir = "img")
        {
            if (file == null || string.IsNullOrWhiteSpace(file.FileName))
                return new Tuple<bool, string, string>(false, "文件为空", "");

            var contentType = file.ContentType;
            var len = file.ContentLength;
            var fileType = new string[] { "image/jpeg", "image/png", "image/gif", "image/jpg" };
            if (!fileType.Any(b => b.Contains(contentType)))
            {
                return new Tuple<bool, string, string>(false, $"_{file.FileName}只能上传{string.Join(",", fileType)}格式的图片", "");
            }

            if (len > 1024 * 1024 * 10)
            {
                return new Tuple<bool, string, string>(false, "上传图片大小只能在8M以下", "");
            }

            string fileKey = dir + "/" + StringHelper.GetNumberAlpha(Path.GetFileNameWithoutExtension(file.FileName)) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + FileHelper.GetFileSuffix(contentType);

            var result = AliyunOssBiz.PutGoodsImgStream(fileKey, file.InputStream);
            if (result.Item1)
                return new Tuple<bool, string, string>(true, "", fileKey);
            else
                return new Tuple<bool, string, string>(false, result.Item2, "");
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="data">流数据</param>
        /// <param name="filetype">格式 "image/jpeg", "image/png", "image/gif", "image/jpg"</param>
        /// <param name="uptype">1 头像 2 付款凭证</param>
        /// <returns></returns>
        public static Tuple<bool, string, string> UpImg(string data, string filetype, string dir = "img")
        {
            if (data.Contains("jpg"))
                filetype = "jpg";
            if (data.Contains("png"))
                filetype = "png";
            if (data.Contains("jpeg"))
                filetype = "jpeg";
            string base64_tag = "base64,";
            if (data.Contains(base64_tag))
            {
                data = data.Substring(data.IndexOf(base64_tag) + base64_tag.Length);//将base64头部信息替换
            }

            Stream stream = Base64ToStream(data.Replace(' ', '+'));

            var fileTypeLists = new string[] { "png", "jpg", "jpeg" };
            if (!fileTypeLists.Any(b => b.Contains(filetype)))
                return new Tuple<bool, string, string>(false, "图片格式错误", "");

            if (stream.Length > 1024 * 1024 * 8)
                return new Tuple<bool, string, string>(false, "上传图片大小只能在8M以下", "");

            //string bucketName = "";
            //if (uptype == 1)
            //    bucketName = "headimg";
            //else if (uptype == 2)
            //    bucketName = "orderimg";

            string key = dir + "/" + DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString("N").Substring(0, 8) + "." + filetype;
            var result = AliyunOssBiz.PutGoodsImgStream(key, stream);
            if (!result.Item1)
                return new Tuple<bool, string, string>(false, "上传失败", "");
            else
                return new Tuple<bool, string, string>(true, "", key);
        }

        /// <summary>
        /// Base64转Stream
        /// </summary>
        private static Stream Base64ToStream(string base64)
        {
            var bytes = Convert.FromBase64String(base64);
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
    }
}
